﻿@using ActualLab.Fusion
@using ActualLab.Fusion.Blazor
@using ActualLab.Fusion.UI
@using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity
@using CleanArchitecture.Blazor.Application.Features.Fusion
@inherits ComputedStateComponent<string[]>
@inject IUserSessionTracker UserSessionTracker
@inject ICurrentUserAccessor CurrentUserAccessor
@inject IStringLocalizer<ActiveUserSession> L
@inject  IJSRuntime JS

@if (!string.IsNullOrEmpty(currentUserId) && State.Value.Any())
{
    <MudAlert Class="mb-2" Severity="MudBlazor.Severity.Error" Variant="Variant.Outlined" Dense="true">@Message</MudAlert>
}

@code {
    [Parameter]
    public string PageComponent { get; set; } = nameof(ActiveUserSession);
    private string Message => $"{string.Join(", ", State.Value)} {L["has this dialog open"]}";
    private string? currentUserId => CurrentUserAccessor.SessionInfo?.UserId;
    [Inject] private UIActionTracker UIActionTracker { get; init; } = null!;
    private TimeSpan UpdateDelay { get; set; } = TimeSpan.FromSeconds(1);
    
    protected override async Task OnInitializedAsync()
    {
        if (CurrentUserAccessor.SessionInfo != null)
        {
            await UserSessionTracker.AddUserSession(PageComponent, CurrentUserAccessor.SessionInfo);
        }
    }

    protected override ComputedState<string[]>.Options GetStateOptions()
     => new() { UpdateDelayer = new UpdateDelayer(UIActionTracker, UpdateDelay) };

    protected override async Task<string[]> ComputeState(CancellationToken cancellationToken)
    {
        var result = await UserSessionTracker.GetUserSessions(PageComponent,cancellationToken);
        if (result.Any())
        {
            return result.Where(x => x.UserId!=currentUserId).Select(x=>x.UserName??string.Empty).ToArray();
        }

        return Array.Empty<string>();
    }

    public override async ValueTask DisposeAsync()
    {
        if (!string.IsNullOrEmpty(currentUserId))
        {
            await UserSessionTracker.RemoveUserSession(PageComponent,currentUserId);
        }
        GC.Collect();
    }
}
